﻿namespace Hidistro.UI.SaleSystem.CodeBehind
{
    using Hidistro.Core;
    using Hidistro.Entities.Commodities;
    using Hidistro.Entities.Sales;
    using Hidistro.Membership.Context;
    using Hidistro.SaleSystem.Shopping;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Globalization;
    using System.Text;
    using System.Web;
    using wnxd.javascript;

    public class ShoppingHandler : IHttpHandler
    {
        private void ClearBrowsedProduct(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            BrowsedProductQueue.ClearQueue();
            context.Response.Write("{\"Status\":\"Succes\"}");
        }

        private void ProcessAddToCartBySkus(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int quantity = int.Parse(context.Request["quantity"], NumberStyles.None);
            string skuId = context.Request["productSkuId"];
            ShoppingCartProcessor.AddLineItem(skuId, quantity);
            ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart();
            context.Response.Write("{\"Status\":\"OK\",\"TotalMoney\":\"" + shoppingCart.GetTotal().ToString(".00") + "\",\"Quantity\":\"" + shoppingCart.GetQuantity().ToString() + "\"}");
        }

        private void ProcessGetSkuByOptions(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int productId = int.Parse(context.Request["productId"], NumberStyles.None);
            string str = context.Request["options"];
            if (string.IsNullOrEmpty(str))
            {
                context.Response.Write("{\"Status\":\"0\"}");
            }
            else
            {
                if (str.EndsWith(","))
                {
                    str = str.Substring(0, str.Length - 1);
                }
                JSShop.Model.aspnet_Members member = null;
                Member m = HiContext.Current.User as Member;
                if (m != null) member = new json(m).TryConvert(typeof(JSShop.Model.aspnet_Members)) as JSShop.Model.aspnet_Members;
                JSShop.Model.Hishop_SKUs productAndSku = new Juse.Interface.ProductBrowser().GetProductAndSku(member, productId, str);
                //SKUItem productAndSku = ShoppingProcessor.GetProductAndSku(productId, str);
                if (productAndSku == null)
                {
                    context.Response.Write("{\"Status\":\"1\"}");
                }
                else
                {
                    StringBuilder builder = new StringBuilder();
                    builder.Append("{");
                    builder.Append("\"Status\":\"OK\",");
                    builder.AppendFormat("\"SkuId\":\"{0}\",", productAndSku.SkuId);
                    builder.AppendFormat("\"SKU\":\"{0}\",", productAndSku.SKU);
                    builder.AppendFormat("\"Weight\":\"{0}\",", productAndSku.Weight.Value.ToString("F0"));
                    builder.AppendFormat("\"Stock\":\"{0}\",", productAndSku.Stock);
                    builder.AppendFormat("\"SalePrice\":\"{0}\"", productAndSku.SalePrice.ToString("F0"));
                    builder.Append("}");
                    if (productAndSku.SalePrice == 0)
                    {
                        Hidistro.Core.Log.logSave("异常价格为0:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        Hidistro.Core.Log.logSave("Json:" + builder.ToString());
                    }
                    context.Response.Write(builder.ToString());
                }
            }
        }
        private void ProcessGetCountDownBySkuId(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            json r = new json(new { error = true });
            int productId;
            if (int.TryParse(context.Request["productId"], out productId))
            {
                string skuId = context.Request["skuId"];
                if (!string.IsNullOrEmpty(skuId))
                {
                    JSShop.Model.Hishop_CountDown info = new Juse.Interface.ProductBrowser().GetCountDownInfo(productId, skuId);
                    Member m = HiContext.Current.User as Member;
                    if (info != null)// && info.Grades!=null && (((m == null || m.IsAnonymous) && info.Grades.Contains("5")) || (m !=null &&info.Grades.Contains(m.GradeId.ToString())))
                    {
                        int count = info.SaleCount == null ? 0 : info.SaleCount.Value;
                        if (info.ProductCount == null || count < info.ProductCount.Value)
                        {
                            r["error"] = false;
                            r["content"] = info.Content;
                            r["time"] = (info.EndDate.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds;
                            r["price"] = info.CountDownPrice;
                            int maxcount = info.MaxCount == null ? 0 : info.MaxCount.Value;
                            if (info.ProductCount != null)
                            {
                                int d = info.ProductCount.Value - count;
                                if (maxcount == 0 || maxcount > d) maxcount = d;
                            }
                            r["count"] = maxcount;
                        }
                    }
                }
            }
            context.Response.Write(r.ToString());
        }

        public void GetProductIsFreight(HttpContext context)
        {
            int productId;
            bool flag = false;
            StringBuilder builder = new StringBuilder();
            if (int.TryParse(context.Request["productId"], out productId))
            {
                JSShop.Model.vw_Hishop_BrowseProductList model = new Juse.Interface.ProductBrowser().GetBrowseProductView(null, productId);
                flag = model.IsfreeShipping || model.IsFreight;
                builder.Append("{");
                builder.Append("\"Status\":\"OK\",");
                builder.AppendFormat("\"Flag\":\"{0}\",", flag);
                builder.AppendFormat("\"ProductId\":\"{0}\",", model.ProductId);
                builder.AppendFormat("\"SaleCount\":\"{0}\"", model.ShowSaleCounts);
                builder.Append("}");
            }
            context.Response.Write(builder.ToString());
        }

        public void GetProductPrice(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            json r = new json(new { error = true });
            string ids = context.Request["productId"];
            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrEmpty(ids))
            {
                Juse.Interface.ProductBrowser pb = new Juse.Interface.ProductBrowser();
                JSShop.Model.DbQueryResultCountDownAndSaleCount model = pb.GetCountDownAndSaleCountByProductIds(ids);
                //List<JSShop.Model.Hishop_CountDown> list = pb.GetCountDownListByProductIds(ids);
                if (model == null)
                {
                    context.Response.Write("{\"CountDown\":[],\"SaleCount\":[]}");
                    return;
                }
                sb.Append("{\"CountDown\":[");
                if (model.CountDownList != null)
                {
                    foreach (var item in model.CountDownList)
                    {
                        sb.Append("{");
                        sb.Append("\"Status\":\"1\",");
                        sb.AppendFormat("\"Product\":\"{0}\",", item.ProductId);
                        sb.AppendFormat("\"Price\":\"{0}\",", Convert.ToInt32(item.CountDownPrice));
                        sb.AppendFormat("\"Time\":\"{0}\"", (item.EndDate.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds);
                        sb.Append("},");
                    }
                    sb.Remove(sb.Length - 1, 1);
                }
                sb.Append("],");
                sb.Append("\"SaleCount\":[");
                if (model.SaleCount != null)
                {
                    foreach (var item in model.SaleCount)
                    {
                        sb.Append("{");
                        sb.Append("\"Status\":\"1\",");
                        sb.AppendFormat("\"Product\":\"{0}\",", item.ProductId);
                        sb.AppendFormat("\"SaleCount\":\"{0}\",", Convert.ToInt32(item.SaleCount));
                        sb.Append("},");
                    }
                    sb.Remove(sb.Length - 1, 1);
                }
                sb.Append("]}");
            }
            context.Response.Write(sb.ToString());
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string str2 = context.Request["action"];
                if (str2 != null)
                {
                    if (!(str2 == "AddToCartBySkus"))
                    {
                        if (str2 == "GetSkuByOptions")
                        {
                            goto Label_0058;
                        }
                        if (str2 == "UnUpsellingSku")
                        {
                            goto Label_0062;
                        }
                        if (str2 == "ClearBrowsed")
                        {
                            goto Label_006C;
                        }
                        if (str2 == "GetCountDownBySkuId")
                        {
                            this.ProcessGetCountDownBySkuId(context);
                            return;
                        }
                        if (str2 == "GetProductIsFreight")
                        {
                            this.GetProductIsFreight(context);
                        }
                        if (str2 == "GetProductPrice")
                        {
                            this.GetProductPrice(context);
                        }
                        if (str2 == "GetAdvertisement")
                        {
                            this.GetAdvertisement(context);
                        }
                        if (str2 == "GetCountDownProduct")
                        {
                            this.GetCountDownProduct(context);
                        }
                        if (str2 == "GetHeatProduct")
                        {
                            GetHeatProduct(context);
                        }
                        if (str2 == "GetPdCountDownProduct")
                        {
                            GetPdCountDownProduct(context);
                        }
                        if (str2 == "IsLogin")
                        {
                            IsLogin(context);
                        }
                    }
                    else
                    {
                        this.ProcessAddToCartBySkus(context);
                    }
                }
                return;
            Label_0058:
                this.ProcessGetSkuByOptions(context);
                return;
            Label_0062:
                this.ProcessUnUpsellingSku(context);
                return;
            Label_006C:
                this.ClearBrowsedProduct(context);
            }
            catch (Exception exception)
            {
                context.Response.ContentType = "application/json";
                context.Response.Write("{\"Status\":\"" + exception.Message.Replace("\"", "'") + "\"}");
            }
        }

        public void IsLogin(HttpContext context)
        {
            context.Response.ContentType = "";
            json r = new json(new { error = true });
            int productId;
            if (int.TryParse(context.Request["productId"], out productId))
            {
                string skuId = context.Request["skuId"];
                if (!string.IsNullOrEmpty(skuId))
                {
                    JSShop.Model.Hishop_CountDown info = new Juse.Interface.ProductBrowser().GetCountDownInfo(productId, skuId);
                    Member m = HiContext.Current.User as Member;
                    if (info != null && info.Grades != null && (((m == null || m.IsAnonymous) && info.Grades.Contains("5")) || (m != null && info.Grades.Contains(m.GradeId.ToString()))))
                    {
                        context.Response.Write("True");
                    }
                    else
                    {
                        context.Response.Write("False");
                    }
                }
            }
        }
        public void GetCountDownProduct(HttpContext context)
        {
            Juse.Interface.ProductBrowser pb = new Juse.Interface.ProductBrowser();
            JSShop.Model.DbQueryResultCountDownProduct list = pb.GetCountDownProductList(6);
            StringBuilder result = new StringBuilder();
            result.Append("{\"TList\":[");
            foreach (var item in list.TList)
            {
                result.Append("{");
                result.AppendFormat("\"CountDownId\":{0},", item.CountDownId);
                result.AppendFormat("\"ProductId\":{0},", item.ProductId);
                result.AppendFormat("\"Time\":\"{0}\",", (item.StartDate.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds);
                result.AppendFormat("\"CountDownPrice\":{0},", item.CountDownPrice);
                result.AppendFormat("\"Image\":\"{0}\",", item.Image);
                result.AppendFormat("\"MobileImage\":\"{0}\",", item.MobileImage);
                result.AppendFormat("\"SalePrice\":{0},", item.SalePrice);
                result.AppendFormat("\"ProductName\":\"{0}\",", item.ProductName);
                result.AppendFormat("\"BrandName\":\"{0}\",", item.BrandName);
                result.AppendFormat("\"CategoryId\":\"{0}\",", item.CategoryId);
                result.AppendFormat("\"IsfreeShipping\":\"{0}\",", item.IsfreeShipping);
                result.AppendFormat("\"IsFreight\":\"{0}\",", item.IsFreight);
                result.AppendFormat("\"Url\":\"{0}\"", Globals.GetSiteUrls().UrlData.FormatUrl("productDetails", new object[] { item.ProductId, item.CategoryUrl }));
                result.Append("},");
            }
            if (list.TList.Count > 0)
            {
                result.Remove(result.Length - 1, 1);
            }
            result.Append("],\"PList\":[");
            foreach (var item in list.PList)
            {
                result.Append("{");
                result.AppendFormat("\"CountDownId\":{0},", item.CountDownId);
                result.AppendFormat("\"ProductId\":{0},", item.ProductId);
                result.AppendFormat("\"Time\":\"{0}\",", (item.EndDate.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds);
                result.AppendFormat("\"CountDownPrice\":{0},", item.CountDownPrice);
                result.AppendFormat("\"Image\":\"{0}\",", item.Image);
                result.AppendFormat("\"MobileImage\":\"{0}\",", item.MobileImage);
                result.AppendFormat("\"SalePrice\":{0},", item.SalePrice);
                result.AppendFormat("\"ProductName\":\"{0}\",", item.ProductName);
                result.AppendFormat("\"BrandName\":\"{0}\",", item.BrandName);
                result.AppendFormat("\"CategoryId\":\"{0}\",", item.CategoryId);
                result.AppendFormat("\"IsfreeShipping\":\"{0}\",", item.IsfreeShipping);
                result.AppendFormat("\"IsFreight\":\"{0}\",", item.IsFreight);
                result.AppendFormat("\"Url\":\"{0}\"", Globals.GetSiteUrls().UrlData.FormatUrl("productDetails", new object[] { item.ProductId, item.CategoryUrl }));
                result.Append("},");
            }
            if (list.PList.Count > 0)
            {
                result.Remove(result.Length - 1, 1);
            }
            result.Append("]}");
            context.Response.Write(result.ToString());
        }

        public void GetPdCountDownProduct(HttpContext context)
        {
            StringBuilder result = new StringBuilder();
            Juse.Interface.ProductBrowser pb = new Juse.Interface.ProductBrowser();
            List<JSShop.Model.CountDownProductInfo> list = pb.GetPdCountDownProductList(0);
            result.Append("[");
            foreach (var item in list)
            {
                result.Append("{");
                result.AppendFormat("\"CountDownId\":{0},", item.CountDownId);
                result.AppendFormat("\"ProductId\":{0},", item.ProductId);
                result.AppendFormat("\"Time\":\"{0}\",", (item.EndDate.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds);
                result.AppendFormat("\"CountDownPrice\":{0},", item.CountDownPrice);
                result.AppendFormat("\"Image\":\"{0}\",", item.Image);
                result.AppendFormat("\"MobileImage\":\"{0}\",", item.MobileImage);
                result.AppendFormat("\"SalePrice\":{0},", item.SalePrice);
                result.AppendFormat("\"ProductName\":\"{0}\",", item.ProductName);
                result.AppendFormat("\"BrandName\":\"{0}\",", item.BrandName);
                result.AppendFormat("\"CategoryId\":\"{0}\",", item.CategoryId);
                result.AppendFormat("\"IsfreeShipping\":\"{0}\",", item.IsfreeShipping);
                result.AppendFormat("\"IsFreight\":\"{0}\",", item.IsFreight);
                result.AppendFormat("\"Url\":\"{0}\"", Globals.GetSiteUrls().UrlData.FormatUrl("productDetails", new object[] { item.ProductId, item.CategoryUrl }));
                result.Append("},");
            }
            if (list.Count>0)
            {
                result.Remove(result.Length - 1, 1);
            }
            result.Append("]");
            context.Response.Write(result.ToString());
        }

        public void GetAdvertisement(HttpContext context)
        {
            string href = context.Request["Href"];
            if (!string.IsNullOrEmpty(href))
            {
                ProductBrowseInfo pb = new ProductBrowseInfo();

            }
        }

        private void ProcessUnUpsellingSku(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int productId = int.Parse(context.Request["productId"], NumberStyles.None);
            int attributeId = int.Parse(context.Request["AttributeId"], NumberStyles.None);
            int valueId = int.Parse(context.Request["ValueId"], NumberStyles.None);
            DataTable table = ShoppingProcessor.GetUnUpUnUpsellingSkus(productId, attributeId, valueId);
            if ((table == null) || (table.Rows.Count == 0))
            {
                context.Response.Write("{\"Status\":\"1\"}");
            }
            else
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("{");
                builder.Append("\"Status\":\"OK\",");
                builder.Append("\"SkuItems\":[");
                foreach (DataRow row in table.Rows)
                {
                    builder.Append("{");
                    builder.AppendFormat("\"AttributeId\":\"{0}\",", row["AttributeId"].ToString());
                    builder.AppendFormat("\"ValueId\":\"{0}\"", row["ValueId"].ToString());
                    builder.Append("},");
                }
                builder.Remove(builder.Length - 1, 1);
                builder.Append("]");
                builder.Append("}");
                context.Response.Write(builder.ToString());
            }
        }

        private void GetHeatProduct(HttpContext context)
        {
            string productId = context.Request["ProductId"];
            Juse.Interface.ProductBrowser pb = new Juse.Interface.ProductBrowser();
            List<JSShop.Model.vw_Hishop_BrowseProductList> list = pb.GetHeatProduct(int.Parse(productId), 4);
            StringBuilder result = new StringBuilder();
            result.Append("[");
            foreach (var item in list)
            {
                result.Append("{");
                result.AppendFormat("\"ThumbnailUrl100\":\"{0}\",", item.ThumbnailUrl100);
                result.AppendFormat("\"SalePrice\":{0},", item.SalePrice);
                result.AppendFormat("\"Url\":\"{0}\"", Globals.GetSiteUrls().UrlData.FormatUrl("productDetails", new object[] { item.ProductId, item.CategoryUrl }));
                result.Append("},");
            }
            if (list.Count>0)
            {
                result.Remove(result.Length - 1, 1);
            }
            result.Append("]");
            context.Response.Write(result.ToString());
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

